using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesMyDraftDetailExpand : System.Web.UI.Page
{
    #region Variables

    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;
    protected readonly int TotalColumns = 7;
    protected MasterBaseCollection ClaimTypes = null;
    protected ClaimItems ResultClaimItems = null;

    #region UsingCreditCard
    protected bool UsingCreditCard
    {
        get
        {
            return (bool)ViewState["UsingCreditCard"];
        }

        set
        {
            ViewState["UsingCreditCard"] = value;
        }
    }
    #endregion

    #region ClaimedCurrency
    protected string ClaimedCurrency
    {
        get
        {
            return ViewState["ClaimedCurrency"].ToString();
        }

        set
        {
            ViewState["ClaimedCurrency"] = value;
        }
    }
    #endregion

    #region ClaimedAmount
    protected decimal ClaimedAmount
    {
        get
        {
            return (decimal)ViewState["ClaimedAmount"];
        }

        set
        {
            ViewState["ClaimedAmount"] = value;
        }
    }
    #endregion

    #region ClaimHeaderID
    protected string ClaimHeaderID
    {

        get
        {
            return ViewState["ClaimHeaderID"].ToString();
        }

        set
        {
            ViewState["ClaimHeaderID"] = value;
        }
    }
    #endregion

    #region ClaimItemID
    protected string ClaimItemID
    {

        get
        {
            return ViewState["ClaimItemID"].ToString();
        }

        set
        {
            ViewState["ClaimItemID"] = value;
        }
    }
    #endregion

    #region ExpandItemIDList
    protected ArrayList ExpandItemIDList
    {
        get
        {
            return (ArrayList)ViewState["ExpandItemIDList"];
        }

        set
        {
            ViewState["ExpandItemIDList"] = value;
        }
    }
    #endregion

    #region ResultTable
    protected DataTable ResultTable
    {

        get
        {
            return (DataTable)ViewState["ResultTable"];
        }

        set
        {
            ViewState["ResultTable"] = value;
        }
    }
    #endregion 

    #region Category

    protected CategoryOfClaim Category
    {
        get
        {
            return (CategoryOfClaim)ViewState["Category"];
        }

        set
        {
            ViewState["Category"] = value;
        }
    }

    #endregion

    #region OriginalLocalAmount
    protected decimal OriginalLocalAmount
    {
        get
        {
            return (decimal)ViewState["OriginalLocalAmount"];
        }

        set
        {
            ViewState["OriginalLocalAmount"] = value;
        }
    }
    #endregion

    #region AmountValidateMessage
    protected string AmountValidateMessage
    {
        get
        {
            string text = (string)ViewState["AmountValidateMessage"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["AmountValidateMessage"] = value;
        }
    }
    #endregion

    #region DateRangeMessage
    protected string DateRangeMessage
    {
        get
        {
            string text = (string)ViewState["DateRangeMessage"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["DateRangeMessage"] = value;
        }
    }
    #endregion

    #region ProperDateMessage
    protected string ProperDateMessage
    {
        get
        {
            string text = (string)ViewState["ProperDateMessage"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["ProperDateMessage"] = value;
        }
    }
    #endregion

    #region DailyRateMessage
    protected string DailyRateMessage
    {
        get
        {
            string text = (string)ViewState["DailyRateMessage"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["DailyRateMessage"] = value;
        }
    }
    #endregion

    #region ExpenseDetail
    protected string ExpenseDetail
    {
        get
        {
            string text = (string)ViewState["ExpenseDetail"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["ExpenseDetail"] = value;
        }
    }
    #endregion

    #region Date
    protected string Date
    {
        get
        {
            string text = (string)ViewState["Date"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["Date"] = value;
        }
    }
    #endregion

    #region Remarks2
    protected string Remarks2
    {
        get
        {
            string text = (string)ViewState["Remarks2"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["Remarks2"] = value;
        }
    }
    #endregion

    #region DailyRate
    protected string DailyRate
    {
        get
        {
            string text = (string)ViewState["DailyRate"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["DailyRate"] = value;
        }
    }
    #endregion

    #region Amount
    protected string Amount
    {
        get
        {
            string text = (string)ViewState["Amount"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["Amount"] = value;
        }
    }
    #endregion

    #region IsPersonal
    protected string IsPersonal
    {
        get
        {
            string text = (string)ViewState["IsPersonal"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["IsPersonal"] = value;
        }
    }
    #endregion

    #region NoExchangeRateMessage
    protected string NoExchangeRateMessage
    {
        get
        {
            string text = (string)ViewState["NoExchangeRateMessage"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["NoExchangeRateMessage"] = value;
        }
    }
    #endregion

    #region MandatoryMessage
    protected string MandatoryMessage
    {
        get
        {
            string text = (string)ViewState["MandatoryMessage"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["MandatoryMessage"] = value;
        }
    }
    #endregion

    #endregion

    #region Events

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();
        this.Table_MessageBox.Visible = false;

        // Building table and rows
        // muz do on every load
        this.BuildTable();

        if (!IsPostBack)
        {
            this.PageComponentSetup();  // setup page component for table grid
            this.SwitchLanguage();
            this.ExpandItemIDList = new ArrayList();
            this.LoadData();
        }
        else
        {
            this.TableGridComponengtSetup();

            for (int x = 0; x < this.ExpandItemIDList.Count; x++)
            {
                this.BuildRow(this.ExpandItemIDList[x].ToString());
            }
        }

        // set personal claim features only for credit card
        // temporaly hide forever
        this.Table_ClaimDetailGrid.Rows[0].Cells[6].Visible = false; //this.UsingCreditCard;

        // Javascripts
        this.GeneralVariable();

    }
    #endregion

    #region Button_Next_Click
    protected void Button_Next_Click(object sender, EventArgs e)
    {
        bool valid = true;
        StringBuilder ErrorMessageBuilder = new StringBuilder("<ul>");

        #region Validate

        if (this.TextBox_DateFrom.Text.Length == 0 || this.TextBox_DateTo.Text.Length == 0)
        {
            ErrorMessageBuilder.AppendLine("<li>" + this.DateRangeMessage + "</li>");
            valid = false;
        }
        else
        {
            try
            {
                // try to convert to date
                DateTime Date1 = SwissArmy.DateConvert(this.TextBox_DateFrom.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat);
                DateTime Date2 = SwissArmy.DateConvert(this.TextBox_DateTo.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat);

                if (Date1 == DateTime.MinValue || Date2 == DateTime.MinValue)
                {
                    ErrorMessageBuilder.AppendLine("<li>" + this.ProperDateMessage + "</li>");
                    valid = false;
                }
            }
            catch (Exception)
            {
                ErrorMessageBuilder.AppendLine("<li>" + this.ProperDateMessage + "</li>");
                valid = false;
            }
        }

        if (this.TextBox_DailyRate.Text.CompareTo("0") == 0)
        {
            ErrorMessageBuilder.AppendLine("<li>" + this.DailyRateMessage + "</li>");
            valid = false;
        }

        ErrorMessageBuilder.AppendLine("</ul>");

        #endregion

        if (valid)
        {
            try
            {                
                DateTime DateFrom = SwissArmy.DateConvert(this.TextBox_DateFrom.Text, this.CurrentPrivateSession.DateFormatInUse);
                DateTime DateTo = SwissArmy.DateConvert(this.TextBox_DateTo.Text, this.CurrentPrivateSession.DateFormatInUse);                
                double Range = SwissArmy.DateDiff(DateCompare.dd, DateTo, DateFrom);
                decimal AverageDailyAmount = (this.TextBox_DailyRate.Text.CompareTo("0") == 0)?(this.ClaimedAmount / decimal.Parse(Range.ToString())):(Convert.ToDecimal(this.TextBox_DailyRate.Text));

                //((TextBox)this.Table_ClaimDetailGrid.Rows[1].Cells[2].Controls[0]).Text = SwissArmy.DateConvert(DateFrom, this.CurrentPrivateSession.DateFormatInUse, "/");                    
                //((TextBox)this.Table_ClaimDetailGrid.Rows[1].Cells[5].Controls[0]).Text = AverageDailyAmount.ToString();                    

                for (int x = 0; x <= Range; x++)
                {
                    this.BuildRow();

                    int CurrentRowIndex = this.Table_ClaimDetailGrid.Rows.Count - 1;
                    ((DropDownList)this.Table_ClaimDetailGrid.Rows[CurrentRowIndex].Cells[1].Controls[0]).SelectedIndex = DropDownList_DetailType.SelectedIndex; //((DropDownList)this.Table_ClaimDetailGrid.Rows[1].Cells[1].Controls[0]).SelectedIndex;
                    ((TextBox)this.Table_ClaimDetailGrid.Rows[CurrentRowIndex].Cells[2].Controls[0]).Text = SwissArmy.DateConvert(DateFrom, this.CurrentPrivateSession.DateFormatInUse, "/");
                    ((TextBox)this.Table_ClaimDetailGrid.Rows[CurrentRowIndex].Cells[3].Controls[0]).Text = this.HiddenRemarks.Value;//((TextBox)this.Table_ClaimDetailGrid.Rows[1].Cells[3].Controls[0]).Text;                   
                    ((TextBox)this.Table_ClaimDetailGrid.Rows[CurrentRowIndex].Cells[5].Controls[0]).Text = AverageDailyAmount.ToString();

                    DateFrom = DateFrom.AddDays(1);

                }

            }
            catch (Exception ex)
            {
                this.CurLogManager.LogError("[GonzalesMyDraftDetailExpand.Button_Next_Click] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
            }
        }
        else
        {
            this.ShowErrorMessage(ErrorMessageBuilder.ToString());
        }
    }
    #endregion

    #region Button_Save_Click
    protected void Button_Save_Click(object sender, EventArgs e)
    {
        if (this.DataValidate())
        {
            if (this.DetailDataCollection())
            {
                using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
                {
                    GonzalesClaimHeader CurClaimHeader = CurClaimManager.GetClaimByInternalID(this.ClaimHeaderID);
                    if (CurClaimHeader != null)
                    {
                        CurClaimHeader.ClaimDetails = this.ResultClaimItems;

                        if (CurClaimManager.UpdateClaimByClaimant(CurClaimHeader))
                        {
                            // update success
                           // Response.Redirect("GonzalesMyDraftDetail.aspx?id=" + this.ClaimHeaderID);
                        }
                        else
                        {
                            this.CurLogManager.LogError("[GonzalesMyDraftDetailExpand.Button_Save_Click] : Error on CurClaimManager.UpdateClaimByClaimant(CurClaimHeader) : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                            this.ShowErrorMessage("[GonzalesMyDraftDetailExpand.Button_Save_Click] : Error on CurClaimManager.UpdateClaimByClaimant(CurClaimHeader) : " + CurClaimManager.ErrorMessage);
                        }

                    }
                    else
                    {
                        this.CurLogManager.LogError("[GonzalesMyDraftDetailExpand.Button_Save_Click] : CurClaimHeader is null : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                        this.ShowErrorMessage("[GonzalesMyDraftDetailExpand.Button_Save_Click] : CurClaimHeader is null : " + CurClaimManager.ErrorMessage);
                    }
                }
            }
        }      
    }
    #endregion

    #region Button_SaveNExit_Click
    protected void Button_SaveNExit_Click(object sender, EventArgs e)
    {
        if (this.DataValidate())
        {
            if (this.DetailDataCollection())
            {
                using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
                {
                    GonzalesClaimHeader CurClaimHeader = CurClaimManager.GetClaimByInternalID(this.ClaimHeaderID);
                    if (CurClaimHeader != null)
                    {
                        CurClaimHeader.ClaimDetails = this.ResultClaimItems;

                        if (CurClaimManager.UpdateClaimByClaimant(CurClaimHeader))
                        {
                            // update success
                            Response.Redirect("GonzalesMyDraftDetail.aspx?id=" + this.ClaimHeaderID);
                        }
                        else
                        {
                            this.CurLogManager.LogError("[GonzalesMyDraftDetailExpand.Button_Save_Click] : Error on CurClaimManager.UpdateClaimByClaimant(CurClaimHeader) : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                            this.ShowErrorMessage("[GonzalesMyDraftDetailExpand.Button_Save_Click] : Error on CurClaimManager.UpdateClaimByClaimant(CurClaimHeader) : " + CurClaimManager.ErrorMessage);
                        }

                    }
                    else
                    {
                        this.CurLogManager.LogError("[GonzalesMyDraftDetailExpand.Button_Save_Click] : CurClaimHeader is null : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                        this.ShowErrorMessage("[GonzalesMyDraftDetailExpand.Button_Save_Click] : CurClaimHeader is null : " + CurClaimManager.ErrorMessage);
                    }
                }
            }
        }
    }
    #endregion

    #region Button_Reset_Click
    protected void Button_Reset_Click(object sender, EventArgs e)
    {
        for (int x = (this.Table_ClaimDetailGrid.Rows.Count - 1); x >= 1; x--)
        {
            this.Table_ClaimDetailGrid.Rows.RemoveAt(x);
            this.ExpandItemIDList.RemoveAt((x-1));
        }
        
    }
    #endregion

    #region Button_Delete_Click

    protected void Button_Delete_Click(object sender, EventArgs e)
    {
        int x = 1;

        while (x < (this.Table_ClaimDetailGrid.Rows.Count))
        {
            if (((CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[0].Controls[0]).Checked)
            {
                for (int y = 0; y < this.ExpandItemIDList.Count; y++)
                {
                    if (this.ExpandItemIDList[y].ToString().CompareTo(this.Table_ClaimDetailGrid.Rows[x].ID) == 0)
                    {
                        this.ExpandItemIDList.RemoveAt(y);
                    }
                }

                this.Table_ClaimDetailGrid.Rows.RemoveAt(x);                
            }
            else
            {
                x++;
            }
        } 
    }

    #endregion

    #region Button_AddMoreLine_Click
    
    protected void Button_AddMoreLine_Click(object sender, EventArgs e)
    {
        for (int x = 0; x < 5; x++)
        {
            this.BuildRow();
        }
    }
    
    #endregion

    #region Button_Cancel_Click
    protected void Button_Cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("GonzalesMyDraftDetail.aspx?id=" + this.ClaimHeaderID);
    }
    #endregion

    #region ImageButton_Cancel_Click
    protected void ImageButton_Cancel_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("GonzalesMyDraftDetail.aspx?id=" + this.ClaimHeaderID);
    }

    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {
        //this.Button_Next.Visible = (this.ExpandItemIDList.Count == 0);

        //this.TextBox_DateFrom.Attributes["onClick"] = this.TextBox_DateTo.Attributes["onClick"] = "popUpCalendar(this, this, '" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "');"; ;
        this.img_calendarFrom.Attributes["onClick"] = "popUpCalendar(this, document.getElementById('TextBox_DateFrom') , '" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "');"; ;
        this.img_calendarTo.Attributes["onClick"] = "popUpCalendar(this, document.getElementById('TextBox_DateTo') , '" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "');"; ;
        this.Button_Save.Attributes["onClick"] = "return Validate();";
        this.Button_SaveNExit.Attributes["onClick"] = "return Validate();";   
        
    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_AmoutLeft.Text = CurLanguageFactory.DisplayValue("AmoutLeft");
                this.Label_ClaimedAmount.Text = CurLanguageFactory.DisplayValue("ClaimedAmount");
                this.Label_DailyRate2.Text = CurLanguageFactory.DisplayValue("DailyRate2");
                this.Label_DateRange.Text = CurLanguageFactory.DisplayValue("DateRange");
                this.Label_Description.Text = CurLanguageFactory.DisplayValue("Description");
                this.Label_DetailType.Text = CurLanguageFactory.DisplayValue("DetailType");
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_Item.Text = CurLanguageFactory.DisplayValue("Item");
                this.Label_ItemRemark.Text = CurLanguageFactory.DisplayValue("ItemRemark");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Label_Remarks.Text = CurLanguageFactory.DisplayValue("Remarks");
                this.Label_To.Text = CurLanguageFactory.DisplayValue("To");

                this.Button_AddMoreLine.Text = CurLanguageFactory.DisplayValue("AddMoreLine");
                this.Button_Cancel.Text = CurLanguageFactory.DisplayValue("Cancel");
                this.Button_Delete.Text = CurLanguageFactory.DisplayValue("Delete");
                this.Button_Next.Text = CurLanguageFactory.DisplayValue("Next");
                this.Button_Reset.Text = CurLanguageFactory.DisplayValue("Reset");
                this.Button_Save.Text = CurLanguageFactory.DisplayValue("Save");
                this.Button_SaveNExit.Text = CurLanguageFactory.DisplayValue("SaveNExit");

                this.DateRangeMessage = CurLanguageFactory.DisplayValue("DateRangeMessage"); ;
                this.ProperDateMessage = CurLanguageFactory.DisplayValue("ProperDateMessage");
                this.DailyRateMessage = CurLanguageFactory.DisplayValue("DailyRateMessage");
                this.ExpenseDetail = CurLanguageFactory.DisplayValue("ExpenseDetail");
                this.Date = CurLanguageFactory.DisplayValue("Date");
                this.Remarks2 = CurLanguageFactory.DisplayValue("Remarks2");
                this.DailyRate = CurLanguageFactory.DisplayValue("DailyRate");
                this.Amount = CurLanguageFactory.DisplayValue("Amount");
                this.IsPersonal = CurLanguageFactory.DisplayValue("IsPersonal");
                this.NoExchangeRateMessage = CurLanguageFactory.DisplayValue("NoExchangeRateMessage");
                this.MandatoryMessage = CurLanguageFactory.DisplayValue("MandatoryMessage");
                this.AmountValidateMessage = CurLanguageFactory.DisplayValue("AmountValidateMessage");
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesMyDraft.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region BuildTable
    
    protected void BuildTable()
    {
        // add all the table header
        TableRow HeaderRow = new TableRow();        

        for (int x = 0; x < this.TotalColumns; x++)
        {
            HeaderRow.Cells.Add(new TableCell());
            HeaderRow.Cells[x].CssClass = "GridViewHeader";
        }

        HeaderRow.Cells[0].Text = ""; HeaderRow.Cells[0].HorizontalAlign = HorizontalAlign.Center;  // delete
        HeaderRow.Cells[1].Text = this.ExpenseDetail; HeaderRow.Cells[1].HorizontalAlign = HorizontalAlign.Center;    
        HeaderRow.Cells[2].Text = this.Date; HeaderRow.Cells[2].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[3].Text = this.Remarks2; HeaderRow.Cells[3].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[4].Text = this.DailyRate; HeaderRow.Cells[4].HorizontalAlign = HorizontalAlign.Center; HeaderRow.Cells[4].Visible = false;
        HeaderRow.Cells[5].Text = this.Amount; HeaderRow.Cells[5].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[6].Text = this.IsPersonal; HeaderRow.Cells[6].HorizontalAlign = HorizontalAlign.Center; 

        this.Table_ClaimDetailGrid.Rows.Add(HeaderRow);      
    }

    #endregion

    #region BuildRow

    protected void BuildRow()
    {
        this.BuildRow(SwissArmy.UniqueID());
    }

    protected void BuildRow(string RowID)
    {
        TableRow NewTableRow = new TableRow();
        NewTableRow.ID = RowID;
        int CellCounter = 0;

        if (!this.ExpandItemIDList.Contains(RowID))
        {
            this.ExpandItemIDList.Add(RowID);
        }

        for (int x = 0; x < this.TotalColumns; x++)
        {
            NewTableRow.Cells.Add(new TableCell());
            NewTableRow.Cells[x].CssClass = "GridViewItem";
            NewTableRow.Cells[x].HorizontalAlign = HorizontalAlign.Center;
        }

        #region 0. Delete Indicator

        CheckBox CheckBoxDelete = new CheckBox();
        CheckBoxDelete.ID = NewTableRow.ID + "_Delete";

        NewTableRow.Cells[CellCounter].Controls.Add(CheckBoxDelete);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(20);

        #endregion

        #region 1. Expense Detail / GL Account

        DropDownList DropDownClaimType = new DropDownList();
        DropDownClaimType.Width = Unit.Percentage(99);
        DropDownClaimType.CssClass = "FormDropDown";
        DropDownClaimType.ID = NewTableRow.ID + "_DropDownClaimType";

        DropDownClaimType.Items.Add(new ListItem("", ""));
        for (int x = 0; x < this.ClaimTypes.Count; x++)
        {
            DropDownClaimType.Items.Add(new ListItem(this.ClaimTypes[x].DisplayName, this.ClaimTypes[x].InternalID));
        }

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(DropDownClaimType);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(200);

        #endregion

        #region 2. Date

        TextBox TextBoxDate = new TextBox();
        TextBoxDate.ID = NewTableRow.ID + "_TextBoxDate";
        TextBoxDate.Width = Unit.Percentage(90);
        TextBoxDate.CssClass = "DetailGridTextBox";
        TextBoxDate.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
        TextBoxDate.Attributes["onClick"] = "popUpCalendar(this, this, '" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "');";

        CellCounter = 2;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxDate);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(80);

        #endregion

        #region 3. Remarks

        TextBox TextBoxRemarks = new TextBox();
        TextBoxRemarks.ID = NewTableRow.ID + "_TextBoxRemarks";
        TextBoxRemarks.CssClass = "DetailGridTextBox";
        TextBoxRemarks.Width = Unit.Percentage(96);

        CellCounter = 3;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxRemarks);
        NewTableRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Left;

        #endregion

        #region 4. Daily Rate

        TextBox TextBoxDailyRate = new TextBox();
        TextBoxDailyRate.ID = NewTableRow.ID + "_TextBoxDailyRate";
        TextBoxDailyRate.CssClass = "DetailGridTextBox";
        TextBoxDailyRate.Text = "0";
        TextBoxDailyRate.Style.Add(HtmlTextWriterStyle.TextAlign, "center");

        CellCounter = 4;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxDailyRate);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(50);
        NewTableRow.Cells[CellCounter].Visible = false;

        #endregion

        #region 5. Amount

        TextBox TextBoxAmount = new TextBox();
        TextBoxAmount.ID = NewTableRow.ID + "_TextBoxAmount";
        TextBoxAmount.CssClass = "DetailGridTextBox";
        TextBoxAmount.Text = "0";
        TextBoxAmount.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
        //TextBoxAmount.Attributes["onChange"] = "EventAmountOnChange(this);";

        CellCounter = 5;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxAmount);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(80);

        #endregion

        #region 6. Is Personal

        CheckBox CheckBoxIsPersonal = new CheckBox();
        CheckBoxIsPersonal.ID = NewTableRow.ID + "_CheckBoxIsPersonal";

        CellCounter = 6;
        NewTableRow.Cells[CellCounter].Controls.Add(CheckBoxIsPersonal);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(20);
        NewTableRow.Cells[CellCounter].Visible = false;

        #endregion

        this.Table_ClaimDetailGrid.Rows.Add(NewTableRow);
    }

    #endregion

    #region BuildParentRow

    protected void BuildParentRow(GonzalesClaimItem ParentItem)
    {
        // add a default row, mark it as parent
        // parent can't be delete away
        this.BuildRow(ParentItem.InternalID);
        //((CheckBox)this.Table_ClaimDetailGrid.Rows[1].Cells[0].Controls[0]).Visible = false;
        ((DropDownList)this.Table_ClaimDetailGrid.Rows[1].Cells[1].Controls[0]).Items.FindByValue(ParentItem.ClaimType.InternalID).Selected = true;
        ((TextBox)this.Table_ClaimDetailGrid.Rows[1].Cells[2].Controls[0]).Text = SwissArmy.DateConvert(ParentItem.ClaimDate, this.CurrentPrivateSession.DateFormatInUse, "/");
        ((TextBox)this.Table_ClaimDetailGrid.Rows[1].Cells[3].Controls[0]).Text = ParentItem.Remarks;
        ((TextBox)this.Table_ClaimDetailGrid.Rows[1].Cells[5].Controls[0]).Text = ParentItem.ClaimedAmount.ToString();        
    }

    #endregion

    #region TableGridComponengtSetup
    protected void TableGridComponengtSetup()
    {
          
        // claim type
        using (GLClaimTypeManager CurGLClaimTypeManager = new GLClaimTypeManager(this.CurrentPrivateSession))
        {
            this.ClaimTypes = CurGLClaimTypeManager.GetActiveClaimTypeInLangByEntity(
                this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage,
                this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.Entity,
                ClaimManager.GetClaimCategoryInCode(this.Category).ToString() );

            if (this.ClaimTypes != null)
            {
                if (this.ClaimTypes != null)
                {
                    for (int x = (this.ClaimTypes.Count - 1); x > 0; x--)
                    {
                        for (int y = 0; y < x; y++)
                        {
                            if (this.ClaimTypes[y].DisplayName.CompareTo(this.ClaimTypes[y + 1].DisplayName) > 0)
                            {
                                GLClaimType Tmp = (GLClaimType)this.ClaimTypes[y];
                                this.ClaimTypes[y] = this.ClaimTypes[y + 1];
                                this.ClaimTypes[y + 1] = Tmp;
                            }
                        }
                    }

                    DropDownList_DetailType.Items.Add(new ListItem("", ""));
                    for (int x = 0; x < this.ClaimTypes.Count; x++)
                    {
                        DropDownList_DetailType.Items.Add(new ListItem(this.ClaimTypes[x].DisplayName, this.ClaimTypes[x].InternalID));
                    }
                }
            }
        }
        
    }
    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
    }
    #endregion

    #endregion

    #region Data Operation

    #region LoadData

    protected void LoadData()
    {
        if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36 &&
            Request.QueryString["cid"] != null && Request.QueryString["cid"].Length == 36)
        {
            this.ClaimHeaderID = Request.QueryString["cid"];
            this.ClaimItemID = Request.QueryString["id"];

            try
            {
                using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
                {
                    GonzalesClaimHeader CurClaimHeader = CurClaimManager.GetClaimByInternalID(this.ClaimHeaderID);
                    if (CurClaimHeader != null)
                    {
                        this.Category = CurClaimHeader.Category;
                        this.TableGridComponengtSetup();

                        ClaimItems CurClaimItems = CurClaimManager.GetClaimItemsByClaimHeaderInLang(this.ClaimHeaderID, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage);

                        decimal TotalAmountForClaimItem = 0;
                        decimal TotalLocalAmountForClaimItem = 0;

                        if (CurClaimItems != null)
                        {
                            // sort the item
                            CurClaimItems.SortByOrder();

                            for (int x = 0; x < CurClaimItems.Count; x++)
                            {
                                GonzalesClaimItem CurClaimItem = (GonzalesClaimItem)CurClaimItems[x];

                                #region Parent Claim Item
                                if (CurClaimItem.InternalID.CompareTo(this.ClaimItemID) == 0)
                                {
                                    this.TextBox_DateFrom.Text = this.TextBox_DateTo.Text = SwissArmy.DateConvert(CurClaimItem.ClaimDate, this.CurrentPrivateSession.DateFormatInUse, "/");
                                    this.ClaimedCurrency = CurClaimItem.ClaimedAmountCurrency.InternalID;
                                    this.LabelValue_Description.Text = CurClaimItem.Description;
                                    this.LabelValue_Remarks.Text = CurClaimItem.Remarks;
                                    this.LabelValue_ExpenseDetail.Text = CurClaimItem.ClaimType.DisplayName;

                                    this.UsingCreditCard = (CurClaimItem.ClaimDetailType == TypeOfClaimDetail.CreditCard);

                                    TotalAmountForClaimItem += CurClaimItem.ClaimedAmount;
                                    TotalLocalAmountForClaimItem += CurClaimItem.AmountOut;

                                    this.DropDownList_DetailType.Items.FindByValue(CurClaimItem.ClaimType.InternalID).Selected = true;
                                    this.HiddenRemarks.Value = CurClaimItem.Remarks;
                                    // create parent row
                                    // parent row kenot delete away
                                    for (int y = x; y < CurClaimItems.Count; y++)
                                    {
                                        GonzalesClaimItem tempClaimItem = (GonzalesClaimItem)CurClaimItems[y];
                                        if (CurClaimItem.InternalID.CompareTo(tempClaimItem.ParentID) == 0)
                                        {
                                            this.BuildParentRow(CurClaimItem);
                                            break;
                                        }
                                    }
                                }

                                #endregion

                                #region Child Claim Item
                                if (CurClaimItem.ParentID.CompareTo(this.ClaimItemID) == 0)
                                {
                                    TotalAmountForClaimItem += CurClaimItem.ClaimedAmount;
                                    TotalLocalAmountForClaimItem += CurClaimItem.AmountOut;

                                    this.BuildRow(CurClaimItem.InternalID);

                                    // fill in the row
                                    int CurTableRowIndex = this.Table_ClaimDetailGrid.Rows.Count - 1;

                                    // claim type
                                    if (CurClaimItem.ClaimType != null)
                                    {
                                        ((DropDownList)this.Table_ClaimDetailGrid.Rows[CurTableRowIndex].Cells[1].Controls[0]).Items.FindByValue(CurClaimItem.ClaimType.InternalID).Selected = true;
                                    }

                                    // claim date
                                    ((TextBox)this.Table_ClaimDetailGrid.Rows[CurTableRowIndex].Cells[2].Controls[0]).Text = SwissArmy.DateConvert(CurClaimItem.ClaimDate, this.CurrentPrivateSession.DateFormatInUse, "/");

                                    // remarks
                                    ((TextBox)this.Table_ClaimDetailGrid.Rows[CurTableRowIndex].Cells[3].Controls[0]).Text = CurClaimItem.Remarks;

                                    // amount claimed
                                    ((TextBox)this.Table_ClaimDetailGrid.Rows[CurTableRowIndex].Cells[5].Controls[0]).Text = CurClaimItem.ClaimedAmount.ToString();

                                    // is personal
                                    ((CheckBox)this.Table_ClaimDetailGrid.Rows[CurTableRowIndex].Cells[6].Controls[0]).Checked = CurClaimItem.IsPersonnal;

                                }
                                #endregion
                            }

                            this.ClaimedAmount = TotalAmountForClaimItem;
                            this.OriginalLocalAmount = TotalLocalAmountForClaimItem;
                            this.LabelValue_AmountClaimed.Text = this.ClaimedCurrency + " " + TotalAmountForClaimItem;

                        }
                        else
                        {
                            string LogID = SwissArmy.UniqueID();
                            this.CurLogManager.LogError(LogID, "[GonzalesMyDraftDetailExpand.LoadData] : Failed at CurClaimManager.GetClaimItemsByClaimHeaderInLang : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                        }
                    }
                    else
                    {
                        string LogID = SwissArmy.UniqueID();
                        this.CurLogManager.LogError(LogID, "[GonzalesMyDraftDetailExpand.LoadData] : Failed at CurClaimManager.GetClaimByInternalID('" + this.ClaimHeaderID + "') : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    }
                }
            }
            catch (Exception ex)
            {
                this.ShowErrorMessage(this.NoExchangeRateMessage);
            }
        }
        else
        {
            this.CurLogManager.LogError("[GonzalesMyDraftDetailExpand.LoadData] : No [id] or [cid]", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }        
    }

    #endregion

    #region DetailDataCollection

    protected bool DetailDataCollection()
    {
        bool smooth = true;

        using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
        {
            this.ResultClaimItems = CurClaimManager.GetClaimItemsByClaimHeader(this.ClaimHeaderID);

            // remove all the child first  
            int counter = 0;
            while (counter < this.ResultClaimItems.Count)
            {
                GonzalesClaimItem CurClaimItem = (GonzalesClaimItem)this.ResultClaimItems[counter];

                if (CurClaimItem.ParentID.CompareTo(this.ClaimItemID) == 0)
                {
                    this.ResultClaimItems.RemoveAt(counter);
                }
                else
                {
                    counter++;
                }
            }

            // now get back the child again            
            if (this.ResultClaimItems != null)
            {
                // get the index first
                int CurClaimIndex = 0, ClaimItemIndexInUsed = 0;
                for (int x = 0; x < this.ResultClaimItems.Count; x++)
                {
                    if (this.ResultClaimItems[x].InternalID.CompareTo(this.ClaimItemID) == 0)
                    {
                        ClaimItemIndexInUsed = CurClaimIndex = x;
                        break;
                    }
                }

                decimal CurrentTotalLocal = 0;

                // update the claim items now
                for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
                {
                    if (x > 1)
                    {
                        GonzalesClaimItem NewClaimItem = CurClaimManager.Clone(((GonzalesClaimItem)this.ResultClaimItems[ClaimItemIndexInUsed]), this.Table_ClaimDetailGrid.Rows[x].ID);
                        NewClaimItem.ParentID = this.ClaimItemID;
                        this.ResultClaimItems.Insert(CurClaimIndex, NewClaimItem);
                    }

                    GonzalesClaimItem CurClaimItem = (GonzalesClaimItem)this.ResultClaimItems[CurClaimIndex];

                    #region Expense Detail / Claim Type

                    DropDownList DropDownListClaimType = (DropDownList)this.Table_ClaimDetailGrid.Rows[x].Cells[1].Controls[0];
                    CurClaimItem.ClaimType = new ClaimType(DropDownListClaimType.SelectedValue, DropDownListClaimType.SelectedItem.Text);

                    #endregion

                    #region Date
                    
                    TextBox TextBoxClaimDate = (TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[2].Controls[0];                    
                    CurClaimItem.ClaimDate = SwissArmy.DateConvert(TextBoxClaimDate.Text, this.CurrentPrivateSession.DateFormatInUse);

                    #endregion

                    #region Remarks

                    TextBox TextBoxRemarks = (TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[3].Controls[0];
                    CurClaimItem.Remarks = TextBoxRemarks.Text;

                    #endregion

                    #region Amount Claimed

                    TextBox TextBoxAmountClaimed = (TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[5].Controls[0];
                    CurClaimItem.ClaimedAmount = Convert.ToDecimal(TextBoxAmountClaimed.Text);
                    //update on 16072012
                    //CurClaimItem.AmountOut = (CurClaimItem.Tax > 0)?((CurClaimItem.ClaimedAmount - ((CurClaimItem.ClaimedAmount * CurClaimItem.Tax) / 100)) * decimal.Parse(CurClaimItem.ExchangeRate.ToString())):(CurClaimItem.ClaimedAmount * decimal.Parse(CurClaimItem.ExchangeRate.ToString()));
                    CurClaimItem.AmountOut = (CurClaimItem.Tax > 0) ? ((CurClaimItem.ClaimedAmount - ((CurClaimItem.ClaimedAmount * CurClaimItem.Tax) / 100)) * Convert.ToDecimal(CurClaimItem.ExchangeRate)) : (CurClaimItem.ClaimedAmount * Convert.ToDecimal(CurClaimItem.ExchangeRate));

                    CurrentTotalLocal += CurClaimItem.AmountOut;

                    #endregion

                    #region Is Personal

                    CheckBox CheckBoxIsPersonal = (CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[6].Controls[0];
                    //CurClaimItem.IsPersonnal = CheckBoxIsPersonal.Checked;

                    #endregion

                    if (DropDownListClaimType.SelectedIndex == 0 && TextBoxClaimDate.Text.Length == 0 && TextBoxRemarks.Text.Length == 0 && TextBoxAmountClaimed.Text.CompareTo("0") == 0)
                    {
                        // no need to save this
                        this.ResultClaimItems.Remove(CurClaimItem);
                    }
                    else
                    {
                        CurClaimIndex++;
                    }
                }

                // check if there is any difference after convert to local amount
                // the difference caused by the exchange rate
                // add the difference back to the last item
                decimal TotalDifferences = this.OriginalLocalAmount - CurrentTotalLocal;                

                //this.ResultClaimItems[this.ResultClaimItems.Count - 1].AmountOut += TotalDifferences;

                // update order
                for (int x = 0; x < this.ResultClaimItems.Count; x++)
                {
                    this.ResultClaimItems[x].Order = x;
                }

            }
            else
            {
                this.CurLogManager.LogError("[GonzalesMyDraftDetailExpand.DetailDataCollection] : ResultClaimItem is null : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage("[GonzalesMyDraftDetailExpand.DetailDataCollection] : ResultClaimItem is null : " + CurClaimManager.ErrorMessage);

                smooth = false;
            }

        }

        return smooth;
    }

    #endregion

    #region DataValidate

    protected bool DataValidate()
    {
        bool smooth = true;        
        bool IsBlank = false;

        for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
        {
            IsBlank = false;

            DropDownList DropDownExpenseDetailType = (DropDownList)this.Table_ClaimDetailGrid.Rows[x].Cells[1].Controls[0];
            TextBox TextBoxClaimDate = (TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[2].Controls[0];
            TextBox TextBoxRemarks = (TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[3].Controls[0];
            TextBox TextBoxAmountClaimed = (TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[5].Controls[0];
            CheckBox CheckBoxIsPersonal = (CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[6].Controls[0];

            if (DropDownExpenseDetailType.SelectedIndex == 0 && TextBoxClaimDate.Text.Length == 0 &&
                TextBoxRemarks.Text.Length == 0 && TextBoxAmountClaimed.Text.CompareTo("0") == 0 && !CheckBoxIsPersonal.Checked)
            {
                IsBlank = true;
            }

            if (!IsBlank)
            {
                if (DropDownExpenseDetailType.SelectedIndex == 0)
                {
                    smooth = false;
                    DropDownExpenseDetailType.CssClass = "ValidatedErrorComponent";
                }
                else
                {
                    DropDownExpenseDetailType.CssClass = "FormDropDown";
                }

                if (TextBoxClaimDate.Text.Length == 0)
                {
                    smooth = false;
                    TextBoxClaimDate.CssClass = "ValidatedErrorComponent";
                }
                else
                {
                    TextBoxClaimDate.CssClass = "DetailGridTextBox";
                }

                if (TextBoxAmountClaimed.Text.CompareTo("0") == 0)
                {
                    smooth = false;
                    TextBoxAmountClaimed.CssClass = "ValidatedErrorComponent";
                }
                else
                {
                    TextBoxAmountClaimed.CssClass = "DetailGridTextBox";
                }
            }

        }        

        if (!smooth)
        {
            this.ShowErrorMessage(this.MandatoryMessage);
        }

        return smooth;
    }

    #endregion

    #endregion

    #region Javascripts

    #region GeneralVariable
    public void GeneralVariable()
    {
        StringBuilder JSBuilder = new StringBuilder();
        JSBuilder.AppendLine("<script language='javascript'>");
        JSBuilder.AppendLine("var TotalAmountClaimed = " + this.ClaimedAmount + ";");
        JSBuilder.AppendLine("var AmountValidateMessage = '" + this.AmountValidateMessage + "';");

        JSBuilder.AppendLine("</script>");

        // done, generate on the page
        if (!this.ClientScript.IsClientScriptBlockRegistered("GeneralVariable"))
        {
            this.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"), "GeneralVariable", JSBuilder.ToString());
        }
    }
    #endregion

    #endregion


}
